/*
 * I write in my free time, for personal using
 * when i fell proud of it, i will give it to public
 * now,have nothing more to say
 */
package com.quangtin3.tunll;

import com.quangtin3.msg.Channel;
import com.quangtin3.msg.Msg;
import com.quangtin3.utils.ControlAble;
import com.quangtin3.utils.TunllException;
import com.quangtin3.utils.TunllLogger;
import java.util.LinkedList;

/**
 * Receive job from Processor by queue, and send to Agent 
 * @author quanghx
 */
public class AgentSender implements Runnable, ControlAble {

    private Channel channel;
    private LinkedList<Msg> jobs = new LinkedList<Msg>();

    public AgentSender(Channel channel) {
        this.channel = channel;
    }

    public void run() {
        //repeat get job and send to Agent
        try {
            TunllLogger.sys.info("thread started");
            while (true) {
                synchronized (jobs) {
                    while (jobs.isEmpty()) {
                        jobs.wait();
                    }
                }
                Msg job = jobs.remove(0);
                channel.sendToAgent(job);
                TunllLogger.sys.debug("sended " + job.toString());
            }
        }
        catch (InterruptedException e) {
            TunllLogger.sys.error("interrupted " + e.getMessage());
        }
        catch (TunllException e) {
            TunllLogger.sys.error("exception " + e.getMessage());
        }
    }

    /**
     * add job to my queue
     * @param job
     */
    public void queue(Msg job) {
        synchronized (jobs) {
            TunllLogger.sys.debug("queue " + job.toString());
            jobs.addLast(job);
            jobs.notify();
        }
    }

    /**
     * close channel associated with this object and
     * stop thread running it. release all resource
     */
    public void requestStop() {

    }

    public void requestSuspend() {

    }

    public void requestResume() {

    }

    public boolean isAlive() {
        return false;
    }

    public synchronized void requestStart() {
    }
}
